<?php
namespace App\Common;

use App\Common\Autoinject;
use ReflectionClass, InvalidArgumentException;

trait AutoinjectTrait {

    private function inject() {
        $class = new ReflectionClass($this);
        $filter = [
            'Service'       => ['Model'],               // service中只支持自动注入model
            'Controller'    => ['Model', 'Service'],
        ];
        $key = current(array_filter(array_keys($filter), fn($it) => str_ends_with($class->getName(), $it)));
        if ($key) {
            foreach($class->getProperties() as $property) {
                if (empty($property->getAttributes(Autoinject::class))) {
                    continue;
                }
                $clazz = $property->getType()->getName();
                if (empty(array_filter($filter[$key], fn($it) => str_ends_with($clazz, $it)))) {
                    throw new InvalidArgumentException("#[Autoinject]定义错误, {$key}中只支持". join(',', $filter[$key]) ."自动注入, path: ". $class->getName());
                }
                $property->setAccessible(true);
                $property->setValue($this, app($clazz));
            }
        }
    }

}